package com.itheima.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Category;
import com.itheima.bean.PageParam;
import com.itheima.common.R;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/category")
@RestController
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    //新增分类
    @PostMapping
    public R add(@RequestBody Category category){

        //1.调用service
        boolean result = categoryService.save(category);

        //2.返回结果
        if(result){
            return R.success("添加分类成功!");
        }
        return R.error("添加分类失败!");
    }

    //分类管理/分页查询
    @GetMapping("/page")
    public R page(PageParam pageParam){

        //1.构建分页对象
        Page<Category> page = new Page<>(pageParam.getPage(),pageParam.getPageSize());

        //2.调用service执行分页查询
        categoryService.page(page);
        //3.响应结果
        return R.success(page);
    }

    //删除分类
    @DeleteMapping
    public R delete(long id){

        int row = categoryService.delete(id);

        if(row>0){
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    //修改分类信息
    @PutMapping
    public R update(@RequestBody Category category){
        boolean b = categoryService.updateById(category);

        if(b){
            return R.success("修改分类信息成功");
        }
            return R.error("修改分类信息失败");
    }

    //根据类型值来查询分类数据
    @GetMapping("/list")
    public R list(Integer type){
        //1.构建条件对象
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //1.1封装条件
        lqw.eq(type != null, Category::getType,type);

        //设置排序
        lqw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        //2.调用Service
        List<Category> categoryList = categoryService.list(lqw);

        return R.success(categoryList);
    }


}
